// 卡片组件注册表
import type { Component } from 'vue'

// 动态导入所有卡片组件
const cardModules = import.meta.glob('./*.vue')

// 卡片组件映射表
export const cardComponentMap: Record<string, () => Promise<Component>> = {}

// 注册所有卡片组件
Object.keys(cardModules).forEach((key) => {
  // 从文件路径中提取组件名称，例如 './SalesCard.vue' -> 'SalesCard'
  const componentName = key.replace('./', '').replace('.vue', '')
  cardComponentMap[componentName] = cardModules[key] as () => Promise<Component>
})

// 获取卡片组件
export async function getCardComponent(componentName: string): Promise<Component | null> {
  const loader = cardComponentMap[componentName]
  if (loader) {
    try {
      const module = await loader()
      return module.default || module
    } catch (error) {
      console.error(`Failed to load card component: ${componentName}`, error)
      return null
    }
  }
  return null
}

// 预加载所有卡片组件
export async function preloadAllCardComponents(): Promise<Record<string, Component>> {
  const components: Record<string, Component> = {}
  
  for (const [componentName, loader] of Object.entries(cardComponentMap)) {
    try {
      const module = await loader()
      components[componentName] = module.default || module
    } catch (error) {
      console.error(`Failed to preload card component: ${componentName}`, error)
    }
  }
  
  return components
}